<?php
namespace Zxf5115\Laravel\Advertising\Providers;

use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Foundation\Application;
use Zxf5115\Laravel\Advertising\Facades\AdvertisingFacade;

/**
 * 广告服务提供者
 */
class AdvertisingServiceProvider extends ServiceProvider
{
  /**
   * 服务是否延迟加载
   */
  protected $defer = true;


  /**
   * 启动服务
   */
  public function boot() : void
  {
    $this->loadRoutes();
    $this->loadMigrations();
    $this->registerAliases();
    $this->configureRouteCaching();
  }


  /**
   * 加载路由文件
   */
  protected function loadRoutes(): void
  {
    $routeFiles = [
      __DIR__ . '/../../routes/platform.php',
      __DIR__ . '/../../routes/api.php',
    ];

    foreach ($routeFiles as $file)
    {
      if (file_exists($file))
      {
        $this->loadRoutesFrom($file);
      }
    }
  }


  /**
   * 加载数据库迁移
   */
  protected function loadMigrations() : void
  {
    $migrationPath = __DIR__ . '/../../database/migrations';

    if(file_exists($migrationPath))
    {
      $this->loadMigrationsFrom($migrationPath);
    }
  }


  /**
   * 注册门面别名
   */
  protected function registerAliases() : void
  {
    AliasLoader::getInstance()->alias('Advertising', AdvertisingFacade::class);
  }


  /**
   * 配置路由缓存
   */
  protected function configureRouteCaching() : void
  {
    if ($this->app->environment('production'))
    {
      $this->app->booted(function ()
      {
        $routes = $this->app['router']->getRoutes();

        $routes->refreshNameLookups();
        $routes->refreshActionLookups();
      });
    }
  }


  /**
   * 延迟加载服务提供列表
   *
   * @return array
   */
  public function provides() : array
  {
    return [
      'advertising',
    ];
  }
}
